//package com.xcw.jac;
//
//import org.apache.zookeeper.*;
//import org.apache.zookeeper.data.Stat;
//
//import java.io.IOException;
//import java.util.concurrent.CountDownLatch;
//
//public class DistributedLock {
//    private static final String ZOOKEEPER_ADDRESS = "localhost:2181";
//    private static final String LOCK_NODE = "/distributed_lock";
//    private static final int SESSION_TIMEOUT = 5000;
//
//    private ZooKeeper zooKeeper;
//    private String lockPath;
//    private CountDownLatch lockAcquiredSignal;
//
//    public DistributedLock() throws IOException, InterruptedException, KeeperException {
//        zooKeeper = new ZooKeeper(ZOOKEEPER_ADDRESS, SESSION_TIMEOUT, null);
//        lockAcquiredSignal = new CountDownLatch(1);
//
//        // 创建分布式锁节点
//        if (zooKeeper.exists(LOCK_NODE, false) == null) {
//            zooKeeper.create(LOCK_NODE, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
//        }
//    }
//
//    public void acquireLock() throws InterruptedException, KeeperException {
//        lockPath = zooKeeper.create(LOCK_NODE + "/lock_", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
//
//        while (true) {
//            Stat currentStat = zooKeeper.exists(lockPath, false);
//
//            if (currentStat == null) {
//                // 锁已经释放，重新尝试获取锁
//                continue;
//            }
//
//            String currentLockName = lockPath.substring(lockPath.lastIndexOf("/") + 1);
//            String[] locks = zooKeeper.getChildren(LOCK_NODE, false).stream()
//                    .filter(lock -> lock.startsWith("lock_"))
//                    .sorted()
//                    .toArray(String[]::new);
//
//            if (locks[0].equals(currentLockName)) {
//                // 当前节点为最小序号节点，获取锁成功
//                break;
//            } else {
//                // 当前节点不是最小序号节点，监听前一个节点
//                String previousLockName = locks[BinarySearch(locks, currentLockName) - 1];
//                String previousLockPath = LOCK_NODE + "/" + previousLockName;
//                Stat previousStat = zooKeeper.exists(previousLockPath, true);
//
//                if (previousStat != null) {
//                    lockAcquiredSignal.await(); // 阻塞等待前一个节点释放锁
//                }
//            }
//        }
//    }
//
//    public void releaseLock() throws InterruptedException, KeeperException {
//        zooKeeper.delete(lockPath, -1);
//        lockAcquiredSignal.countDown();
//    }
//
//    private int BinarySearch(String[] array, String target) {
//        int left = 0;
//        int right = array.length - 1;
//
//        while (left <= right) {
//            int mid = left + (right - left) / 2;
//            int result = array[mid].compareTo(target);
//
//            if (result == 0) {
//                return mid;
//            } else if (result < 0) {
//                left = mid + 1;
//            } else {
//                right = mid - 1;
//            }
//        }
//
//        return left;
//    }
//
//    public void close() throws InterruptedException {
//        zooKeeper.close();
//    }
//
//    public static void main(String[] args) {
//        try {
//            DistributedLock lock = new DistributedLock();
//            lock.acquireLock();
//
//            // 执行需要同步的代码块
//            System.out.println("获得分布式锁，执行任务...");
//
//            lock.releaseLock();
//            lock.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//}
